package com.ligq.common.utils

import android.Manifest
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentManager

const val TAG = "common_ligq"

object PermissionUtils {
    val permissions = arrayOf(
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.CAMERA,
        Manifest.permission.RECORD_AUDIO
    )
    private val grantedPermissions = mutableListOf<String>()
    fun permissionGranted(permission: String) = grantedPermissions.contains(permission)
    fun addPermission(permission: String) {
        grantedPermissions.add(permission)
    }

    fun checkPermission(
        fragmentActivity: FragmentActivity,
        permissionArray: Array<out String> = permissions, result: ((grantResults: IntArray) -> Unit)? = null
    ) {
        getPermissionsFragment(fragmentActivity.supportFragmentManager)?.checkPermission(result)
    }

    fun clearPermissions() {
        grantedPermissions.clear()
    }

    fun getPermissions() = grantedPermissions

    private fun getPermissionsFragment(fragmentManager: FragmentManager): PermissionFragment? {
        var permissionsFragment: PermissionFragment? =
            findPermissionsFragment(fragmentManager)
        val isNewInstance = permissionsFragment == null
        if (isNewInstance) {
            permissionsFragment = PermissionFragment()
            fragmentManager
                .beginTransaction()
                .add(permissionsFragment, TAG)
                .commitNow()
        }
        return permissionsFragment
    }

    private fun findPermissionsFragment(fragmentManager: FragmentManager): PermissionFragment? {
        return fragmentManager.findFragmentByTag(TAG) as PermissionFragment?
    }
}